package cn.lg.soar.database.datascope;

import cn.lg.soar.core.annotations.DataScope;
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList;

/**
 * @author luguoxiang 469599794@qq.com
 * @Date: 2023/10/26 15:46
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class SoarDataPermissionHandler implements DataPermissionHandler {

    /**
     * @param where 原SQL Where 条件表达式
     * @param mappedStatementId Mapper接口方法ID（cn.lg.soar.system.auth.mapper.DataScopeMapper.getById）
     * @return
     */
    @Override
    public Expression getSqlSegment(Expression where, String mappedStatementId) {
        // 是否忽略
        if (DataScopeHolder.isIgnore(mappedStatementId)) {
            return where;
        }
        DataScope dataScope = DataScopeHolder.getResourceCode();
        if (dataScope == null) {
            return where;
        }
        // 查询数据规则
        Expression expression = DataScopeUtils.getExpression(dataScope.code(), dataScope.table());
        if (expression == null) {
            // 全部数据权限
            return where;
        }
        // 拼接筛选条件
        if (expression instanceof ParenthesedExpressionList) {
            return new AndExpression(expression, where);
        }
        return new AndExpression(new ParenthesedExpressionList<>(expression), where);
    }


}
